package com.zhongjh.app.phone.main.fragment.my

import android.Manifest.permission.CAMERA
import android.Manifest.permission.WRITE_EXTERNAL_STORAGE
import android.annotation.SuppressLint
import android.os.Bundle
import android.widget.Toast
import androidx.core.content.res.ResourcesCompat
import androidx.lifecycle.lifecycleScope
import com.afollestad.materialdialogs.LayoutMode
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.bottomsheets.BottomSheet
import com.afollestad.materialdialogs.lifecycle.lifecycleOwner
import com.afollestad.materialdialogs.list.listItems
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions
import com.gyf.immersionbar.ImmersionBar
import com.permissionx.guolindev.PermissionX
import com.zhongjh.albumcamerarecorder.listener.OnResultCallbackListener
import com.zhongjh.app.R
import com.zhongjh.app.databinding.FragmentMyBinding
import com.zhongjh.app.phone.MyApplication
import com.zhongjh.app.phone.shoppingcart.ShoppingCartViewManager
import com.zhongjh.app.phone.shoppingcart.shoppingCartCountFlow
import com.zhongjh.app.util.AlbumCameraRecorderUtil
import com.zhongjh.common.entity.LocalFile
import com.zhongjh.common.entity.MultiMedia
import com.zhongjh.mvvmibatis.base.ui.BaseFragment
import com.zhongjh.mvvmibatis.entity.State
import com.zhongjh.mvvmibatis.utils.GlideCircleBorderTransform
import dagger.hilt.android.AndroidEntryPoint

/**
 * 我的
 * @author zhongjh
 * @date 2022/5/30
 */
@AndroidEntryPoint
class MyFragment : BaseFragment<FragmentMyBinding>(R.layout.fragment_my) {

    private val mShoppingCartViewManager: ShoppingCartViewManager by lazy {
        ShoppingCartViewManager(mBinding.tvShoppingCartCount, 0)
    }

    /**
     * 圆形头像设置
     */
    private val options by lazy {
        RequestOptions()
            .error(
                ResourcesCompat.getDrawable(
                    resources,
                    R.drawable.placeholder_res,
                    MyApplication.instance.theme
                )
            )
            .placeholder(R.mipmap.ic_launcher)
            .centerCrop()
            .diskCacheStrategy(DiskCacheStrategy.ALL)
            .transform(
                GlideCircleBorderTransform(
                    4F,
                    ResourcesCompat.getColor(
                        MyApplication.instance.resources,
                        com.zhongjh.mvvmibatis.R.color.white,
                        MyApplication.instance.theme
                    )
                )
            )
            .diskCacheStrategy(DiskCacheStrategy.DATA)
    }

    override fun initParam(savedInstanceState: Bundle?) {
    }

    override fun initialize() {
        // 圆形头像
        setPhoto("https://gitee.com/zhongjh/MvvmIbatis/raw/master/server/images/11.jpg")
    }

    override fun initListener() {
        mBinding.imgPhoto.setOnClickListener {
            // 弹出底部菜单
            showBottomSheetPhoto()
        }
    }

    override fun initObserver() {
        lifecycleScope.launchWhenStarted {
            shoppingCartCountFlow.collect {
                when (it) {
                    is State.Success -> {
                        mShoppingCartViewManager.amount = it.data
                    }
                    else -> {}
                }
            }
        }
    }

    override fun onResume() {
        super.onResume()
        ImmersionBar
            .with(this)
            .titleBar(mBinding.vTop)
            .statusBarColorTransformEnable(false)
            .navigationBarColor(com.zhongjh.mvvmibatis.R.color.white)
            .statusBarDarkFont(true)
            .navigationBarDarkIcon(true)
            .init()
    }

    /**
     * 显示底部菜单，关于拍照选择照片的
     */
    @SuppressLint("CheckResult")
    private fun showBottomSheetPhoto() {
        val items: MutableList<String> = ArrayList()
        items.add("拍照")
        items.add("相册")
        context?.let {
            MaterialDialog(it, BottomSheet(LayoutMode.WRAP_CONTENT)).show {
                listItems(null, items, null, false) { _, _, _ ->
                    requestPhotoPermissions()
                }
                negativeButton(R.string.cancel)
                lifecycleOwner(activity)
            }
        }
    }

    /**
     * 请求拍照权限
     */
    private fun requestPhotoPermissions() {
        PermissionX.init(activity)
            .permissions(CAMERA, WRITE_EXTERNAL_STORAGE)
            .onExplainRequestReason { scope, deniedList ->
                scope.showRequestReasonDialog(deniedList, "使用该功能需要这些权限", "OK", "Cancel")
            }
            .onForwardToSettings { scope, deniedList ->
                scope.showForwardToSettingsDialog(deniedList, "您需要在“设置”中手动允许必要的权限", "OK", "Cancel")
            }
            .request { allGranted, _, _ ->
                if (allGranted) {
                    // 启动相册
                    openImage()
                } else {
                    Toast.makeText(context, "权限被拒绝，无法使用该功能", Toast.LENGTH_LONG).show()
                }
            }
    }

    private fun openImage() {
        activity?.let {
            AlbumCameraRecorderUtil.openImage(
                it,
                object : OnResultCallbackListener {
                    override fun onResult(result: List<LocalFile>) {
                        result[0].path?.let { it1 -> setPhoto(it1) }
                    }

                    override fun onResultFromPreview(result: List<MultiMedia>, apply: Boolean) {
                    }
                }
            )
        }
    }

    /**
     * 设置头像图片
     */
    private fun setPhoto(value: String) {
        // 圆形头像
        Glide.with(MyApplication.instance)
            .load(value)
            .apply(options)
            .into(mBinding.imgPhoto)
    }
}